#!/usr/bin/env python
#-*- coding:utf-8 -*-

"""
    PySeq0 - a python sequencer
    (c) by Tobias Sauer 2011
    Copyright: GPL v2 only
    http://leichtdio.de
    tobias@leichtdio.de
    
    Google Code:
    http://pyseq0.leichtdio.de
"""

from functools import partial
from itertools import izip, count
import sys
import logging
_log = logging.getLogger("gui")

import pyglet
from simplui import *

import song

class UITools:
    def __init__(self):
        self.width = 1024
        self.heigth = 700
        self.songbox = None

    def load_file(self, arg, button):
        if self.songbox:
            frame.remove(self.songbox)

        jukebox.set_songid(arg)
        loops = jukebox.get_loops()
        loopbuttons = []
        drums = jukebox.get_drums()
        drumbuttons = []
        ## LOOPBUTTON
        for i, loop in izip(count(), loops):
            loopbuttons.append(Button ("Loop %s #%s" %(loop.meta["name"], i),
                                        action=partial(self.play_loop, i)))
        ## DRUMBUTTON
        for i, drum in izip(count(), drums):
            drumbuttons.append(Button ("Drum %s #%s" %(drum.meta["name"], i),
                                        action=partial(self.play_drum, i)))

        self.songbox = Dialogue('SongBox', x=100, y=400, content=
        VLayout(autosizex=True, hpadding=0, children=[
                HLayout(children=loopbuttons),
                HLayout(hpadding=5, children=drumbuttons),
            ]
        ))

        frame.add(self.songbox)

    def autoconnect(self, button):
        self.load_file(jukebox.auto_song_select(), button)

    def play_drum(self, arg, button):
        jukebox.drum(arg)

    def play_loop(self, arg, button):
        jukebox.loop(arg)

    def quit(self, button):
        sys.exit()

    def dummy(self, button):
        _log.info("Not implemented")

    def file_loader(self, button):
        _log.info("Not implemented")

    def filebrowser(self):
        #filebrowser_content = [Button('Load File', action=self.file_loader)]
        filebrowser_content = []
        ## evtl von Jukebox verwalten lassen; Jetzt erstmal alle in songs/
        songdic = jukebox.songs
        for i, song in izip(count(), songdic):
            filebrowser_content.append(Button(song.meta["name"],
                                       action=partial(self.load_file, i))
                                       )
        ## ++AutoConnect
        filebrowser_content.append(Button("Auto Connect",
                                          action=self.autoconnect))
        return Dialogue('Projects', x=900, y=650, content=
                        VLayout(autosizex=True,
                                hpadding=0,
                                children=filebrowser_content)
                       )


if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG,
                        format="[%(name)s] %(message)s (%(levelname)s)")

    ui = UITools()

    window = pyglet.window.Window(ui.width, ui.heigth,
                                  caption="pyseq0 - v 0.1 rc2",
                                  vsync=False)
    theme = Theme("themes/pywidget")
    frame = Frame(theme, w=ui.width, h=ui.heigth)
    window.push_handlers(frame)
    #

    jukebox = song.Jukebox()
    jukebox.scan_dir("songs")

    dialogue = Dialogue('MainWindow', x=10, y=650, content=
        VLayout(autosizex=True, hpadding=0, children=[
            FoldingBox('stats', content=
                VLayout(children=[
                    Label('0.0 fps', name='fps_label'),
                    ])
                ),
            FoldingBox('settings', content=
                VLayout(children=[
                    Button('Preference', action=ui.dummy),
                    Button('Quit', action=ui.quit),
                    ])
                ),
            ])
        )

    frame.add( dialogue )
    frame.add( ui.filebrowser())

    # in the on_draw event, we just call frame.draw()
    @window.event
    def on_draw():
        window.clear()
        frame.draw()

    # schedule an empty update function
    # this forces the window to be refreshed regularly
    def update(dt):
        pass

    pyglet.clock.schedule(update)

    # schedule a update function to be called less often
    def update_stats(dt):
        # if the dialogue is onscreen, update the fps counter
        if dialogue.parent != None:
            fps = pyglet.clock.get_fps()
            # retrieve the named element from the gui
            element = frame.get_element_by_name('fps_label')
            # and change the text, to display the current fps
            element. text = '%.1f fps' % (fps)

    pyglet.clock.schedule_interval(update_stats, 0.5)

    # change the background colour
    pyglet.gl.glClearColor(0.8, 0.8, 1.0, 1.0)

    # finally, run the application...
    pyglet.app.run()
